package nianbao;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;

import java.util.List;

/**
 * 消息解码器
 */
public class ByteToMessageProtocalDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        //先读取数据的长度，前4个字节是长度
        int length = 0;
        if(byteBuf.readableBytes() >= 4){
            length = byteBuf.readInt();
        }
        if(byteBuf.readableBytes() >= length){
            //如果有长度，就向后读取一定长度的字节，转换为字符串
            byte[] bytes = new byte[length];
            byteBuf.readBytes(bytes);
            String str = new String(bytes,0,length, CharsetUtil.UTF_8);
            //添加解码的结果
            list.add(new MessageProtocal(str));
        }else{
            System.out.println("数据长度不足，等待...");
        }
    }
}
